<%@page import="com.nxu.entity.BookBean"%>
<%@page import="com.nxu.entity.CartItemBean"%>
<%@page import="com.nxu.biz.impl.BooksBizImpl"%>
<%@page import="com.nxu.biz.BooksBiz"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    String isbn = request.getParameter("isbn");
    BooksBiz biz = new BooksBizImpl();
    BookBean book = biz.getBookByIsbn(isbn);

    if (book != null && book.isActive()) {
        Map<String, CartItemBean> cart = (Map<String, CartItemBean>) session.getAttribute("cart");
        if (cart == null) {
            cart = new HashMap<>();
            session.setAttribute("cart", cart);
        }
        CartItemBean cartItem = cart.get(isbn);
        if (cartItem == null) {
            cart.put(isbn, new CartItemBean(book, 1));
        } else {
            cartItem.setQuantity(cartItem.getQuantity() + 1);
        }
        response.sendRedirect("viewCart.jsp");
    } else {
        // 商品不存在或已下架，重定向回详情页并显示错误信息
        response.sendRedirect("detail.jsp?isbn=" + isbn + "&error=book_unavailable");
    }
%>